﻿/*
 * Created by SharpDevelop.
 * User: mac
 * Date: 26.01.2007
 * Time: 16:35
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using TagTool.Core;
using TagTool.GraphicTypes;
using System.IO;

namespace TagTool.Nodes.Misc
{
	public class WriteFile : BaseNode
	{
		
		private InputSlot shape;
		private bool tin;
		
		public WriteFile()
		{
			this.Name = "WriteFile";
			shape = new InputSlot(this, "Shape", new Shape());
		}
		
		public override void Update(Object sender)
		{
			if ((bool)TriggerIn.Value == true && tin == false && shape.Value != null)
			{
				String path = ProjectManager.Instance.AppDir + "\\sessions\\" + ProjectManager.Instance.SessionName;
				if (!System.IO.Directory.Exists(path))
				{
					System.IO.Directory.CreateDirectory(path);
				}
				String fileName = path + "\\" + DateTime.Now.ToFileTime() + ".tag";
				Stream stream = File.Open(fileName, FileMode.Create);
				StreamWriter writer = new StreamWriter(stream);
				writer.AutoFlush = true;
				((Shape)shape.Value).Save(writer);
				long start;
				long act;
				// Metadata
				writer.WriteLine("Metadata");
				start = writer.BaseStream.Position;
				writer.WriteLine(String.Format("{0:000000000000}", 0));
				
				writer.Write(ProjectManager.Instance.UI.MetaData);
				
				act = writer.BaseStream.Position;
				writer.BaseStream.Seek(start, 0);
				writer.WriteLine(String.Format("{0:000000000000}", act - start));
				writer.BaseStream.Seek(act, 0);
				
				stream.Close();
			}
			
			tin = (bool)TriggerIn.Value;
		}
		
		[NodeAttribute(SlotType.Input, Show = true)]
        public InputSlot Shape
        {
            get { return shape; }
        }
		
	}
}
